﻿Imports System.Convert
Public Class DateFunctions
    Public Shared Function MonthLastDay(ByVal dCurrDate As Date) As Date
        Dim dFirstDayNextMonth As Date
        Try
            MonthLastDay = Nothing
            dFirstDayNextMonth = DateSerial(Year(dCurrDate), Month(dCurrDate) + 1, 1)
            MonthLastDay = DateAdd("d", -1, dFirstDayNextMonth)
        Catch ex As Exception
            Return Now
        End Try
    End Function
    Public Shared Function GetDateFromString(InStr As String) As Date
        'Assume Instr is in the form YYYYMMDD
        If InStr.Length > 8 Then InStr = InStr.Substring(0, 8)
        If InStr <> "" Then Return New Date(ToInt32(InStr.Substring(0, 4)), ToInt32(InStr.Substring(4, 2)), ToInt32(InStr.Substring(6, 2)))
        Return Now
    End Function
    Public Shared Function GetDateTimeFromString(InStr As String) As Date
        'Assume Instr is in the form YYYYMMDDHHmm
        If InStr = "" Or Val(InStr) = 0 Then
            Return Now
        Else
            Return New Date(CInt(Left(InStr, 4)), CInt(Mid(InStr, 5, 2)), CInt(Mid(InStr, 7, 2)), CInt(Mid(InStr, 9, 2)), CInt(Mid(InStr, 11, 2)), 0)
        End If
    End Function
    Shared Function GetDateString(DTValue As DateTime) As String
        Return Strings.Format(DTValue, "yyyyMMdd")
    End Function
    Shared Function GetDateTimeString(DTValue As DateTime) As String
        Return Strings.Format(DTValue, "yyyyMMddHHmm")
    End Function
    Shared Function GetDateTimeSecondString(DTValue As DateTime) As String
        Return Strings.Format(DTValue, "yyyyMMddHHmmss")
    End Function
    Shared Function GetTimeAddMinutesAsString(StartTime As String, MinutesToAdd As Integer) As String
        If Len(StartTime) > 4 Then StartTime = Strings.Right(StartTime, 4)
        Dim tStartTime As DateTime = New DateTime(2000, 1, 1, CInt(Strings.Left(StartTime, 2)), CInt(Strings.Right(StartTime, 2)), 0).AddMinutes(MinutesToAdd)
        Return Format(tStartTime, "HHmm")
    End Function
    Shared Function GetTimeStringfromDate(DatetimeValue As DateTime) As String
        Return Format(DatetimeValue, "HHmm")
    End Function
    Shared Function GetWeekNumber(ByVal pDate As Date) As Integer
        Dim span As TimeSpan = pDate - New Date(pDate.Year, 1, 1)
        Return (CInt(span.TotalDays) \ 7) + 1
    End Function
End Class
